package cn.wygandwdn.core.transport.client.handler;

import cn.wygandwdn.common.enumeration.ResponseInfo;
import cn.wygandwdn.common.message.RpcResponse;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description:    处理服务端响应的消息,通过Promise来接收和处理消息
 * @author: WYG
 * @time: 2021/10/27 16:05
 */
@ChannelHandler.Sharable
public class RpcClientResponseHandler extends SimpleChannelInboundHandler<RpcResponse> {

    private static final Logger log = LoggerFactory.getLogger(RpcClientResponseHandler.class);
    /**
     * key-序号,请求的序号,用于关联请求和响应
     * value-promise,封装结果的容器
     */
    public static final Map<Long, Promise<Object>> PROMISE = new ConcurrentHashMap<>();


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponse msg) {
        log.debug("msg: {}", msg);
        // 请求id
        long sequenceId = msg.getSequenceId();
        Promise<Object> promise = PROMISE.remove(sequenceId);
        log.debug("promise: {}", promise);
        // 非空判断
        if (promise != null) {
            if (msg.getCode().equals(ResponseInfo.HANDLE_SUCCESS.getCode())) {
                log.debug("调用成功: {}", msg.getMessage());
                promise.setSuccess(msg.getData());
            } else {
                log.debug("调用失败: {}", msg.getMessage());
                promise.setFailure(msg.getException());
            }
        } else {
            log.error("序号为:[{}]的请求已处理完成", sequenceId);
        }
    }

}
